﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;
using DevExpress.Web.ASPxEditors;

namespace TireService.Web.UserControls
{
    public partial class ucCreateTask : System.Web.UI.UserControl
    {

        #region Public Properties

        public int CustomerId
        {
            get
            {
                if (ViewState["_customerid"] != null)
                    return (int)ViewState["_customerid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_customerid"] = value;
            }
        }

        public int CarId
        {
            get
            {
                if (ViewState["_carid"] != null)
                    return (int)ViewState["_carid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_carid"] = value;
            }
        }

        public int TireSetId
        {
            get
            {
                if (ViewState["_tiresetid"] != null)
                    return (int)ViewState["_tiresetid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_tiresetid"] = value;
            }
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            //TireServiceDB db = new TireServiceDB();

            //// Bind dropdown with tasktypes
            //ddlTaskType.TextField = "Description";
            //ddlTaskType.ValueField = "TaskTypeId";
            //ddlTaskType.DataSource = db.GetTaskTypes();
            //ddlTaskType.DataBind();

            //// Bind dropdown with cars for selected customer
            //ddlCar.DataSource = db.GetCustomerCars(this.CustomerId);
            ////ddlCar.TextField = "RegistrationNumber";
            //ddlCar.ValueField = "CarId";
            //ddlCar.DataBind();

            //BindTireSet(this.CarId, db);
        }

        private void LoadCreateTask(TireServiceDB db, int CustomerId, int CarId, int TireSetId)
        {
            if (CustomerId != 0)
            {
                Customer customer = db.GetCustomer(CustomerId);

                if (customer != null)
                {
                    this.CustomerId = CustomerId;

                    // Bind dropdown with tasktypes
                    ddlTaskType.TextField = "Description";
                    ddlTaskType.ValueField = "TaskTypeId";
                    ddlTaskType.DataSource = db.GetTaskTypes();
                    ddlTaskType.DataBind();

                    // Bind dropdown with cars for selected customer
                    ddlCar.DataSource = db.GetCustomerCars(CustomerId);
                    ddlCar.TextField = "RegistrationNumber";
                    ddlCar.ValueField = "CarId";
                    ddlCar.DataBind();

                    if (CarId != 0)
                    {
                        this.CarId = CarId;
                        ddlCar.Items.FindByValue(this.CarId.ToString()).Selected = true;

                        // Bind dropdown with tiresets for selected car
                        BindTireSet(this.CarId, db);

                        if (TireSetId != 0)
                        {
                            this.TireSetId = TireSetId;
                            ddlTireSet.Items.FindByValue(this.TireSetId.ToString()).Selected = true;
                        }
                    }
                }
                else
                {
                    // Error
                    throw new ArgumentException("Kunde ikke fundet");
                }
            }
            else
            {
                // Error
                throw new ArgumentException("Kunde ikke fundet");
            }
        }

        protected void callbackCreateTaskPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // Get CallBackCreateTaskAction
            string[] CallBackCreateTaskAction = e.Parameter.Split('|');

            // Instantiate datalayer
            TireServiceDB db = new TireServiceDB();

            int customerid = Convert.ToInt32(CallBackCreateTaskAction[1]);
            int carid = 0;
            int tiresetid = 0;

            try
            {
                carid = Convert.ToInt32(CallBackCreateTaskAction[2]);
            }
            catch (Exception)
            {

            }

            try
            {
                tiresetid = Convert.ToInt32(CallBackCreateTaskAction[3]);
            }
            catch (Exception)
            {

            }

            if (CallBackCreateTaskAction[0] == "NoAction")
            {
                LoadCreateTask(db, customerid, carid, tiresetid);
            }

            if (CallBackCreateTaskAction[0] == "SelectedTaskTypeChanged")
            {
                // Function that shows correct task type wizard in UI
                if (Convert.ToInt32(CallBackCreateTaskAction[4]) == (int)Shared.TaskType.ServiceDrive)
                {
                    pServiceDriveTaskPanel.Visible = true;
                    LoadServiceDrivePanel(db, customerid);
                    pStockTaskPanel.Visible = false;
                    pBackofficeTaskPanel.Visible = false;
                    pStockMovePanel.Visible = false;
                }

                if (Convert.ToInt32(CallBackCreateTaskAction[4]) == (int)Shared.TaskType.StockTask)
                {
                    pServiceDriveTaskPanel.Visible = false;
                    pStockTaskPanel.Visible = true;
                    LoadStockTaskPanel(db, customerid, carid, tiresetid);
                    pBackofficeTaskPanel.Visible = false;
                    pStockMovePanel.Visible = false;
                }

                if (Convert.ToInt32(CallBackCreateTaskAction[4]) == (int)Shared.TaskType.BackofficeTask)
                {
                    pServiceDriveTaskPanel.Visible = false;
                    pStockTaskPanel.Visible = false;
                    pBackofficeTaskPanel.Visible = true;
                    pStockMovePanel.Visible = false;
                }

                if (Convert.ToInt32(CallBackCreateTaskAction[4]) == (int)Shared.TaskType.StockMove)
                {
                    pServiceDriveTaskPanel.Visible = false;
                    pStockTaskPanel.Visible = false;
                    pBackofficeTaskPanel.Visible = false;
                    pStockMovePanel.Visible = true;
                }

                //carid = Convert.ToInt32(CallBackCreateTaskAction[2]);
                //tiresetid = Convert.ToInt32(CallBackCreateTaskAction[3]);

                LoadCreateTask(db, customerid, carid, tiresetid);
            }

        }

        protected void ddlTireSet_Callback(object source, CallbackEventArgsBase e)
        {
            // Instantiate datalayer
            TireServiceDB db = new TireServiceDB();

            BindTireSet(Convert.ToInt32(e.Parameter), db);
        }

        private void BindTireSet(int CarId, TireServiceDB db)
        {
            // Bind dropdown with tasktypes
            ddlTireSet.ValueField = "TireSetId";
            ddlTireSet.TextField = "TireSetId";
            ddlTireSet.DataSource = db.GetCustomerCarTireSetViews(CarId);
            ddlTireSet.DataBind();
        }

        /// <summary>
        /// Function for loading UI panel for service drive task creation
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="CustomerId">Customer to create task for</param>
        private void LoadServiceDrivePanel(TireServiceDB db, int CustomerId)
        {
            ddlServiceDriveType.TextField = "Description"; 
            ddlServiceDriveType.ValueField = "TaskDetailTypeId";
            ddlServiceDriveType.DataSource = db.GetTaskDetailTypes((int)(Shared.TaskType.ServiceDrive));
            ddlServiceDriveType.DataBind();

            Customer customer = db.GetCustomer(CustomerId);

            if (customer == null)
            {
                // Error
                throw new ArgumentException("Kunde ikke fundet");
            }

            // Show possible adresses to select from
            ddlSelectAddress.Items.Clear();
            string add1 = customer.Address + ", " + customer.ZipCode + " " + customer.City;
            string add2 = customer.SecondaryAddress + ", " + customer.SecondaryZipCode + " " + customer.SecondaryCity;
            if (customer.OnPrimaryAddressInPrimeTime)
            {
                add1 += " (8-16)";
            }
            else
            {
                add2 += " (8-16)";
            }

            string add3 = "-- Anden adresse --";
            ddlSelectAddress.Items.Add(add1, 0);
            ddlSelectAddress.Items.Add(add2, 1);
            ddlSelectAddress.Items.Add(add3, 2);
        }

        private void LoadStockTaskPanel(TireServiceDB db, int CustomerId, int CarId, int TireSetId) 
        {
            ddlStockTaskType.TextField = "Description";
            ddlStockTaskType.ValueField = "TaskDetailTypeId";
            ddlStockTaskType.DataSource = db.GetTaskDetailTypes((int)(Shared.TaskType.StockTask));
            ddlStockTaskType.DataBind();

            // Only show tasks that do not already have childdependecy created
            ddlDependentOnTask.DataSource = db.GetDependentChildTasks(CustomerId, CarId, TireSetId, false);
            //ddlDependentOnTask.TextField = "TaskId";
            ddlDependentOnTask.ValueField = "TaskId";
            ddlDependentOnTask.DataBind();

            // Only show tasks that do not already have dependecy created
            ddlDependentOfTask.DataSource = db.GetTasksWithDependency(CustomerId, CarId, TireSetId, false);
            //ddlDependentOfTask.TextField = "TaskId";
            ddlDependentOfTask.ValueField = "TaskId";
            ddlDependentOfTask.DataBind();
        }

        protected void SetNullItem(object control)
        {
            ASPxComboBox cb = (ASPxComboBox)control;
            if (cb != null)
            {
                ListEditItem item = new ListEditItem("(ingen)", "");
                cb.Items.Insert(0, item);
                cb.SelectedItem = item;
            }
        }

        protected void ddlDependentOnTask_DataBound(object sender, EventArgs e)
        {
            SetNullItem(sender);
        }

        protected void ddlDependentOfTask_DataBound(object sender, EventArgs e)
        {
            SetNullItem(sender);
        }

        /// <summary>
        /// Function that creates a service drive task
        /// </summary>
        protected void callbackServiceDriveTaskPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {   
            // Description on values recieved
            // 0: Action text
            // 1: CustomerId
            // 2: CarId
            // 3: TireSetId
            // 4: TaskTypeId
            // 5: TaskDetailTypeId
            // 6: Address selection (0, 1 or 2)
            // 7: Address
            // 8: ZipCode
            // 9: City
            // 10: Remark to address (Optional)
            // 11: Note to employee (Optional)

            // Get values
            string[] values = e.Parameter.Split('|');

            // Instantiate datalayer and business layer
            TireServiceDB db = new TireServiceDB();
            TaskBLL bll = new TaskBLL();

            string Address = "", ZipCode = "", City = "", CommentToAddress = "";
            int SelectedAddress = Convert.ToInt32(values[6]);
            if (SelectedAddress == 0 | SelectedAddress == 1)
            {
                Customer customer = db.GetCustomer(Convert.ToInt32(values[1]));

                if (SelectedAddress == 0)
                {
                    // Customer Primary address selected
                    Address = customer.Address;
                    ZipCode = customer.ZipCode;
                    City = customer.City;
                    CommentToAddress = customer.CommentToAddress;
                }
                if (SelectedAddress == 1)
                {
                    // Customer Secondary address selected
                    Address = customer.SecondaryAddress;
                    ZipCode = customer.SecondaryZipCode;
                    City = customer.SecondaryCity;
                    CommentToAddress = customer.CommentToSecondaryAddress;
                }
            }

            if (SelectedAddress == 2)
            {
                // Custom address selected
                Address = values[7].ToString();
                ZipCode = values[8].ToString();
                City = values[9].ToString();
                CommentToAddress = values[10].ToString();
            }

            // Get UserId
            Guid UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());

            // Create servicedrive task
            Task task = bll.CreateTask(db,
                                        null,
                                        Convert.ToInt32(values[4]),
                                        Convert.ToInt32(values[5]),
                                        (int)Shared.TaskTypeStatus.ServiceDrive_Created,
                                        Convert.ToInt32(values[1]),
                                        Convert.ToInt32(values[2]),
                                        Convert.ToInt32(values[3]),
                                        Address,
                                        ZipCode,
                                        City,
                                        0,
                                        CommentToAddress,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        values[11].ToString(),
                                        1,
                                        UserId,
                                        true);

            // Commit changes to database
            db.SubmitChanges();

            // Close database connection
            db.Dispose();            
        }

        protected void callbackStockTaskPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // Description on values received
            // 0: Action text
            // 1: CustomerId
            // 2: CarId
            // 3: TireSetId
            // 4: TaskTypeId
            // 5: TaskDetailTypeId
            // 6: Dependent on othertask
            // 7: Dependent of this task
            // 8: Amount
            // 9: Note to employee (Optional)

            // Get values
            string[] values = e.Parameter.Split('|');

            // Instantiate datalayer and business layer
            TireServiceDB db = new TireServiceDB();
            TaskBLL bll = new TaskBLL();

            int? dependenttaskid = null;
            //if (values[6] != "(ingen)") dependenttaskid = Convert.ToInt32(values[6]);
            if (values[6] != "null") dependenttaskid = Convert.ToInt32(values[6]);
            decimal Amount = Convert.ToDecimal(values[8]);

            // Get UserId
            Guid UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());

            // Create servicedrive task
            Task task = bll.CreateTask(db,
                                        dependenttaskid,
                                        Convert.ToInt32(values[4]),
                                        Convert.ToInt32(values[5]),
                                        (int)Shared.TaskTypeStatus.StockTask_Created,
                                        Convert.ToInt32(values[1]),
                                        Convert.ToInt32(values[2]),
                                        Convert.ToInt32(values[3]),
                                        null,
                                        null,
                                        null,
                                        0,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        values[9].ToString(),
                                        Amount,
                                        UserId,
                                        true);
            
            // Add dependency on other task
            //if (values[7] != "(ingen)")
            if (values[7] != "null")
	        {
                Task dependenttask = db.GetTask(Convert.ToInt32(values[7]));

                bll.AddDependencyToTask(db, task, dependenttask);
	        }

            // Commit changes to database
            db.SubmitChanges();

            // Close database connection
            db.Dispose();   
        }

        protected void callbackBackofficeTaskPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // TODO: Implement functionality
        }

        protected void callbackStockMovePanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // TODO: Implement functionality
        }
    }
}